package managers.messengerManager;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.SortedMap;
import java.util.TreeMap;

import managers.DBManager;
import managers.messengerManager.services.ChangePersonalMessageService;
import managers.socialNetworkManagers.SocialNetworkFeedbackManager;
import managers.socialNetworkManagers.SocialNetworkManager;
import utils.SpotUserData;
import utils.UserData;

public class SpotDBDataManager implements DataManager {

	private MessengerManager manager = MessengerManager.getSharedInstance();
	
	private TreeMap<Integer, UserData> userData = new TreeMap<Integer, UserData>();
	
	
	public SpotDBDataManager () throws SQLException {
	}
	
	
	public void retrieveUsers() throws SQLException {

		Connection conn = DBManager.getConnection();
		Statement stmt = conn.createStatement();
		String query = "select id, firstname, surname, usertype from spotmessenger.users";
		ResultSet rs = stmt.executeQuery(query);

		while (rs.next()) {
			UserData user = new SpotUserData(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4));
			userData.put((Integer) user.getProperty("id"), user);
			manager.getFeedbackManager().addUserView(user);
			manager.getFeedbackManager().update();
		}

		DBManager.closeResources(stmt, rs);
	}

	@Override
	public SortedMap<Integer, UserData> getUsers () {
		return userData;
	}
	
	@Override
	public UserData getUser(int userId) {
		return userData.get(userId);
	}


	@Override
	public void updatePersonalMessage(String message) {
		new ChangePersonalMessageService(message).start();
	}
	
	@Override
	public void retrievePersonalMessage () throws SQLException {
		Statement stmt = DBManager.getConnection().createStatement();
		String query = "select personalmessage from spotmessenger.users where id= "+MessengerManager.getSharedInstance().getUserId();
		ResultSet rs = stmt.executeQuery(query);
		rs.next();
		manager.getFeedbackManager().setPersonalMessage (rs.getString(1));
		
		DBManager.closeResources(stmt, rs);
	}

}
